package com.gombe.credit.app.ui.activity

import android.Manifest
import android.content.Intent
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.gombe.credit.app.R
import com.gombe.credit.app.base.app.GombeCreditActivityStackManager
import com.gombe.credit.app.common.CommonActivity
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditConfigs
import com.gombe.credit.app.databinding.ActGombeCreditLaunchPageBinding
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.ui.dialog.DialogGombeCreditPermissionReason
import com.gombe.credit.app.ui.dialog.DialogGombeCreditUpdate
import com.gombe.credit.app.utils.GombeCreditTitleBarUtil
import com.gombe.credit.app.utils.helper.GombeCreditAnalysisHelper
import com.gombe.credit.app.utils.helper.GombeCreditConfigsHelper
import com.gombe.credit.app.utils.helper.GombeCreditPermissionHelper
import com.gombe.credit.app.utils.helper.GombeCreditUpdateHelper
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.gombe.credit.app.utils.shared.GombeCreditSharedHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedKey
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import org.json.JSONObject
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import java.util.TimeZone

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/5 20:18
 * @Annotation：
 */
class ActGombeCreditLaunch: CommonActivity(),EasyPermissions.RationaleCallbacks {
    lateinit var binding: ActGombeCreditLaunchPageBinding
    private val PERMISSION_REQUEST_CODE : Int = 10001;
    //是否需要去登录， 只有时区接口的 时区转发字段发生变化时，需要改变此值
    private var isToLogin = false

    private var updateHelper: GombeCreditUpdateHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                // TODO: 更新成功，进入主界面
                showLaunchIntentPage()
            } else {
                // 1、用户取消或失败，不处理，继续进入主界面
                // 2、如果需要强制，建议跳转应用商店，拦截进入主界面
                if (updateHelper == null) {
                    showLaunchIntentPage()
                    return@registerForActivityResult
                }
                updateHelper?.handleNoUpdate {
                    showLaunchIntentPage()
                }
            }
        }

    override fun takeGombeCreditRootView(): View? {
        binding = ActGombeCreditLaunchPageBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        GombeCreditTitleBarUtil.setStatusBarLightMode(this, true)
        isInterceptBack(true)
        //关闭所有页面
        GombeCreditActivityStackManager.finishAllActivity(ActGombeCreditLaunch::class.java)
        //启动需要重置审核中、放款中显示的公告提示次数
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_DIALOG_NOTICE_NUM,0)
    }

    override fun initGombeCreditListener() {
        binding.textAppName.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                loadGombeCreditLaunchTimeZoneAction()
            }
        })
    }

    override fun takeGombeCreditData() {
//        lifecycleScope.launch {
//            delay(1000)
//        }

//        lifecycleScope.launch {
//            showGombeCreditLoading()
//           val result = withContext(Dispatchers.IO){
//                delay(5000)
//                "start"
//            }
//            if (result == "start"){
//                showGombeCreditToast("开始加载获取时区")
//                loadGombeCreditLaunchTimeZoneAction()
//            }
//        }
        loadGombeCreditLaunchTimeZoneAction()
    }

    /**
     * 时区转发成功
     */
    fun showGombeCreditTimeZoneRequestData(data: String) {
        var timeZone = ""
        var zoneCode = ""
        var zoneCountry = ""

        data.split(",").apply {
            if (this.isNotEmpty()){
                timeZone = this[0].trim()
            }
            if (this.size >= 2){
                zoneCode = this[1].trim()
            }
            if (this.size >= 3){
                zoneCountry = this[2].trim()
            }
        }
        //获取上次保存的时区转发，仅用于改变已登录状态下，是否需要重新登录判断
        val saveTimeZone = GombeCreditSharedHelper.takeGombeCreditSharedString(GombeCreditSharedKey.GOMBECREDIT_TIMEZONE)
        if (saveTimeZone != timeZone){
            isToLogin = true
        }

        //保存转发路径
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_TIMEZONE,timeZone)
        //保存转发地区 区号
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_TIMEZONE_CODE,zoneCode)
        //保存国家标识
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_TIMEZONE_COUNTRY,zoneCountry)

        //初始化analysis lib 赋值 转发地区
        GombeCreditAnalysisHelper.initAnalysisLibAtZoneSuccess()
        //添加埋点
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.LAUNCH_START)

        loadGombeCreditLaunchConfigsAction()
    }

    /**
     * 获取时区
     */
    private fun loadGombeCreditLaunchTimeZoneAction(){
        showGombeCreditLoading()
        val httpUrl = GombeCreditApiUrl.takeLaunchTimeZoneUrl()
        val params = JSONObject().apply {
            put("p", GombeCreditConfigs.GOMBECREDIT_APPNAME)
            put("tz", TimeZone.getDefault().id)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                showGombeCreditTimeZoneRequestData(data.optString("data"))
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取客服配置
     */
    private fun loadGombeCreditLaunchConfigsAction(){
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_APP_INFO_PATH)
            put("product", GombeCreditConfigs.GOMBECREDIT_APPNAME)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideGombeCreditLoading()
                val obj = data.optJSONObject("obj")
                //保存所有数据
                if (obj != null) {
//                    val customize = obj.optJSONObject("customize")
//                    val customData = customize.optJSONObject("customData")
//                    val testVersion = JSONObject()
//                    testVersion.put("isMustUpdate",false)
//                    testVersion.put("versionCode","2")
//                    testVersion.put("versionName","2.0.0")
//                    testVersion.put("versionRemark","1.A brand new UI design.$2.Update more secure data processing.$3.Resolve known bugs, optimize code, and enhance user experience.")
//                    customData.put("release",testVersion)
                    GombeCreditConfigsHelper.insertGombeCreditConfigData(obj.toString())
                }
                //是否强制更新版本
                val isUpdate = GombeCreditConfigsHelper.isGombeCreditUpdateMust()
                if (isUpdate){
                    showGombeCreditUpdateDialog()
                    return
                }
                showLaunchIntentPage()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 执行跳转逻辑
     */
    fun showLaunchIntentPage(){
        //权限页操作状态 : 0未操作  1已同意  -1拒绝
        val permissionStatus = GombeCreditSharedHelper.takeGombeCreditSharedInt(GombeCreditSharedKey.GOMBECREDIT_PERMISSIONS_STATUS)
        //权限列表未操作 -> 进入权限列表
        if (permissionStatus == 0){
            showGombeCreditPermissionsReasonDialog()
            return
        }

        //是否显示引导页
        if (!GombeCreditSharedHelper.takeGombeCreditSharedBoolean(GombeCreditSharedKey.GOMBECREDIT_SHOW_GUIDE_PAGE)){
            showGombeCreditGuidePage()
            return
        }

        //已登录 - 进入主页
        if (GombeCreditSharedHelper.takeGombeCreditSharedBoolean(GombeCreditSharedKey.GOMBECREDIT_LOGIN)){
            //初始化analysis lib 赋值 用户id 和 token
            GombeCreditAnalysisHelper.initAnalysisLibAtLoginSuccess()
            showGombeCreditMainPage()
            return
        }
        //进入登录页面
        showGombeCreditLoginPage()
    }

    /**
     * 进入引导页
     */
    private fun showGombeCreditGuidePage() {
        onIntent(ActGombeCreditGuide::class.java)
        finish()
    }

    /**
     * 进入登录页
     */
    private fun showGombeCreditLoginPage() {
        onIntent(ActGombeCreditUserLogin::class.java)
        finish()
    }

    /**
     * 进入主页
     */
    private fun showGombeCreditMainPage() {
        //时区转发发生变化 需要重新登录
        if (isToLogin){
            showGombeCreditLoginPage()
            return
        }
        onIntent(ActGombeCreditMain::class.java)
        finish()
    }

    /**
     * 进入权限申明列表
     */
    private fun showGombeCreditPermissionListPage(){
        onIntent(ActGombeCreditPermissionList::class.java)
        finish()
    }

    /**
     * 版本更新Dialog
     */
    private fun showGombeCreditUpdateDialog(){
        val updateDialog = DialogGombeCreditUpdate(this,"Launch page",object : DialogGombeCreditUpdate.IDialogCallback{
            override fun onUpdateClick() {
                try {
                    if (updateHelper == null){
                        updateHelper = GombeCreditUpdateHelper(activity = this@ActGombeCreditLaunch, forceUpdate = true, updateLauncher)
                    }
                    updateHelper?.checkAndStartUpdate { showLaunchIntentPage() }
                } catch (e: Exception) {
                    showLaunchIntentPage()
                }
            }
        })
        updateDialog.show()
    }

    /**
     * SMS权限声明dialog
     */
    private fun showGombeCreditPermissionsReasonDialog(){
        val item = GombeCreditPermissionHelper.queryGombeCreditPermissionItem1()
        val requestPermission = item.optString("permission")
        val dialog = DialogGombeCreditPermissionReason(this,requestPermission,object : DialogGombeCreditPermissionReason.IDialogCallback{
            override fun onClick(view: View?) {
                when(view?.id){
                    R.id.btnAgree -> {//同意
                        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_REASON_DIALOG_AGREE,requestPermission)
                        requestGombeCreditPermissionAction()
                    }
                    R.id.btnDeny -> {//拒绝
                        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_REASON_DIALOG_DENY,requestPermission)
                        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_PERMISSIONS_STATUS,-1)
                        showGombeCreditPermissionListPage()
                    }
                }
            }
        })
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
        dialog.showGombeCreditPermissionReasonData(item)
    }


    /**
     * 申请权限
     */
    private fun requestGombeCreditPermissionAction(){
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_PERMISSIONS_STATUS,1)
        // TODO:  权限说明
        val requestReason = getString(R.string.gombe_credit_permission_sms_why_reason) + "\n" + getString(R.string.gombe_credit_permission_sms_do_reason) + "\n" + getString(R.string.gombe_credit_permission_sms_data_safety_reason)
        EasyPermissions.requestPermissions(this, requestReason,PERMISSION_REQUEST_CODE,Manifest.permission.READ_SMS)
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        GombeCreditLogger.e("Permission page onPermissionsGranted, code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_REQUEST_CODE){
            addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_SYSTEM_AGREE,Manifest.permission.READ_SMS)
            showGombeCreditPermissionListPage()
        }
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        GombeCreditLogger.e("onPermissionsDenied code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_REQUEST_CODE){
            addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_SYSTEM_DENY, Manifest.permission.READ_SMS)
            GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_PERMISSIONS_STATUS,-1)
            showGombeCreditPermissionListPage()
        }
    }

    override fun onRationaleAccepted(requestCode: Int) {
        GombeCreditLogger.e("onRationaleAccepted, code: $requestCode")
    }

    override fun onRationaleDenied(requestCode: Int) {
        GombeCreditLogger.e("onRationaleDenied, code: $requestCode")
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE){
            // 判断权限是否申请成功
            val hasPermissions = EasyPermissions.hasPermissions(this, Manifest.permission.READ_SMS)
            if (hasPermissions){
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_SYSTEM_AGREE,Manifest.permission.READ_SMS)
                showGombeCreditPermissionListPage()
            }
        }
    }

    override fun requestTryAgain() {
        super.requestTryAgain()
        takeGombeCreditData()
    }

    override fun onResume() {
        super.onResume()
        try {
            updateHelper?.resumeIfInProgress()
        } catch (e: Exception) {
            //
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.LAUNCH_END)
    }
}